/* eslint-disable react/jsx-wrap-multilines */
/* eslint-disable jsx-a11y/anchor-is-valid */
import React, { useState, useEffect } from "react";
import {
  Button,
  TextField,
  Box,
  Typography,
  FormControlLabel,
  Checkbox,
  Grid,
  ThemeProvider,
  Avatar,
  InputAdornment,
  IconButton,
  createTheme,
} from "@mui/material";
import { Link, useNavigate, useSubmit, useActionData } from "react-router-dom";
import LockOutlinedIcon from "@mui/icons-material/LockOutlined";
import { Visibility, VisibilityOff } from "@mui/icons-material";
import { loginUser, validateLoginData } from "../../api/userLoginRegister.js";
import { Copyright, LilySnack } from "../../components/common/Common.jsx";
import LoginRegisterContainer from "./Common.jsx";
/**
 * Sign in action function
 * @param {request} request data
 * @returns redirect if successful, id if failed
 */
export async function action({ request }) {
  const formData = await request.formData();
  const account = formData.get("account");
  const password = formData.get("password");
  // Simple validation
  const res = { fail: true };
  res.err = await loginUser({ account, password });
  if (res.err === "") {
    return res;
  } else {
    return res;
  }
}

// 定义一个默认的主题对象
const defaultTheme = createTheme();
/**
 * 登录组件
 */
export default function Login() {
  // 路由跳转
  const [account, setAccount] = useState("");
  const [password, setPassword] = useState("");
  // 设置“记住我”
  const [rememberMe, setRememberMe] = useState(false);
  // Snackbar
  const [snackbarMes, setSnackbarMes] = useState({
    text: undefined,
    open: false,
    severity: "warning",
  });
  // 密码状态
  const [showPassword, setShowPassword] = useState(false);
  const passwordType = showPassword ? "password" : "text";

  // 密码明文状态转换
  const toChangePasswordState = () => {
    setShowPassword((prevState) => !prevState);
  };
  // Submit and action outcome
  const submit = useSubmit();
  const res = useActionData();
  const navigate = useNavigate();
  // 记住当前用户
  useEffect(() => {
    const storedAccount = localStorage.getItem("account");
    const storedPassword = localStorage.getItem("password");
    const storedRememberMe = localStorage.getItem("rememberMe");

    if (storedRememberMe === "true" && storedAccount && storedPassword) {
      setAccount(storedAccount);
      setPassword(storedPassword);
      setRememberMe(true);
    }
  }, []);
  /**
   * 是否需要弹出snackbar
   */
  useEffect(() => {
    if (res?.fail && res.err !== "") {
      setSnackbarMes({ text: res.err, open: true, severity: "error" });
    } else if (res?.err === "") {
      setSnackbarMes({
        text: "登录成功, 三秒后返回",
        open: true,
        severity: "success",
      });
      //三秒后返回主页面
      setTimeout(() => {
        navigate("/");
      }, 3000);
    }
  }, [res]);

  //登录
  const handleLogin = async (e) => {
    e.preventDefault();
    const err = validateLoginData(account, password);
    if (err.length === 0) {
      submit(
        { account, password },
        {
          method: "post",
          encType: "application/x-www-form-urlencoded",
        }
      );
    } else {
      setSnackbarMes({ text: err, open: true, severity: "error" });
    }
  };

  return (
    <ThemeProvider theme={defaultTheme}>
      <LoginRegisterContainer>
        <Avatar sx={{ m: 1, bgcolor: "grey.150" }}>
          <LockOutlinedIcon />
        </Avatar>
        <Typography component="h1" variant="h5">
          登录
        </Typography>
        <Box sx={{ mt: 1 }}>
          {/*提交表单 */}
          <form onSubmit={handleLogin}>
            {/* 用户名 */}
            <TextField
              margin="normal"
              required
              fullWidth
              id="account"
              label="账号"
              name="account"
              autoComplete="account"
              autoFocus
              value={account}
              onChange={(e) => setAccount(e.target.value)}
            />

            {/* 密码 */}
            <TextField
              margin="normal"
              required
              fullWidth
              name="password"
              label="密码"
              type={passwordType}
              id="password"
              autoComplete="current-password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              InputProps={{
                endAdornment: (
                  <InputAdornment position="end">
                    <IconButton onClick={toChangePasswordState} edge="end">
                      {showPassword ? <VisibilityOff /> : <Visibility />}
                    </IconButton>
                  </InputAdornment>
                ),
              }}
            />

            {/* 记住我 */}
            <FormControlLabel
              control={
                <Checkbox
                  value="remember"
                  color="primary"
                  checked={rememberMe}
                  onChange={(e) => setRememberMe(e.target.checked)}
                />
              }
              label="记住我"
            />
            {/* 登录键 */}
            <Button
              type="submit"
              fullWidth
              variant="contained"
              sx={{ mt: 3, mb: 2 }}>
              登录
            </Button>
          </form>
          <Grid container>
            {/* 忘记密码 */}
            <Grid item xs>
              {/*需要完善这个忘记密码 */}
              <Link href="#" variant="body2">
                忘记密码?
              </Link>
            </Grid>
            {/* 跳转注册界面 */}
            <Grid item>
              <Button variant="body2" component={Link} to={"/register"}>
                {"没有账户? 注册"}
              </Button>
            </Grid>
          </Grid>
        </Box>
        {/* 版权信息 */}
        <Copyright sx={{ mt: 8, mb: 2 }} />
      </LoginRegisterContainer>
      <LilySnack
        duration={snackbarMes.duration}
        open={snackbarMes.open}
        onClose={(event, reason) => {
          if (reason === "clickaway") {
            return;
          }
          setSnackbarMes({ ...snackbarMes, open: false });
        }}
        severity={snackbarMes.severity}
        text={snackbarMes.text}
      />
    </ThemeProvider>
  );
}
